﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebStore.Domain.Entities;
using WebStore.Domain.Entities.Enum;
using WebStore.Domain.Entities.Model;
using WebStore.Infrastructure.Service.Interface;

namespace WebStore.Infrastructure.Service.Implementation
{
    public class AdminService : IAdminService
    {
        private readonly Entities _entities;

        public AdminService(Entities entities)
        {
            _entities = entities;
        }

        public bool RealizeOrder(int orderId, int adminId)
        {
            var order = _entities.Orders.FirstOrDefault(x => x.Id == orderId);
            order.RealizeDate = DateTime.Now;
            order.OrderStatus = OrderStatus.Complete;
            order.RealizedById = adminId;
            _entities.SaveChanges();
            return true;
        }

        public bool RejectOrder(int orderId, int adminId)
        {
            var order = _entities.Orders.FirstOrDefault(x => x.Id == orderId);
            order.RealizeDate = DateTime.Now;
            order.OrderStatus = OrderStatus.Rejected;
            order.RealizedById = adminId;
            _entities.SaveChanges();
            return true;
        }

        public bool EditProduct(int? id, string name, string description, decimal price, int categoryId, byte[] photo, out string errorMessage)
        {
            errorMessage = null;
            if (id != null)
            {
                var product = _entities.Products.FirstOrDefault(x => x.Id == id);
                product.Name = name;
                product.Description = description;
                product.Price = price;
                product.CategoryId = categoryId;
                if(photo!=null)
                    product.Photo = photo;
            }
            else
            {
                var product = new Product
                                  {
                                      CategoryId = categoryId,
                                      Description = description,
                                      Name = name,
                                      Price = price,
                                      Photo = photo
                                  };
                _entities.Products.Add(product);
            }
            _entities.SaveChanges();
            return true;
        }

        public bool DeleteProduct(int id)
        {
            var product = _entities.Products.FirstOrDefault(x => x.Id == id);
            if (product == null)
                return false;
            product.IsDeleted = true;
            return true;
        }
    }
}
